<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\AddCartRequest;
use App\Http\Resources\CartResource;
use App\Service\CartService;
use App\Service\ConfigService;
use App\Http\Controllers\Controller;

class CartController extends Controller
{
    protected $cartService;

    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    /**
     * 购物车列表
     *
     * @return mixed
     */
    public function index(ConfigService $configService)
    {
        $cartItems = $this->cartService->get();
        $cartPriceSum = $cartItems->sum('total');
        $freightPrice = $configService->getFreightPrice();
        return $this->success(['carts' => CartResource::collection($cartItems), 'total_amount' => $cartPriceSum, 'freightPrice' => $freightPrice]);
    }

    /**
     * 添加购物车
     *
     * @param AddCartRequest $request
     * @return mixed
     */
    public function store(AddCartRequest $request)
    {
        $this->cartService->add(
            $request->input('sku_id'),
            $request->input('amount'),
            $request->input('type'),
            $request->input('product_id')
        );

        return $this->message('操作成功');
    }

    /**
     * 删除购物车
     *
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        if($this->cartService->remove(explode(',', $id))){

            return $this->message('删除成功');
        }else {
            return $this->failed('删除失败');
        }
    }
}
